const express = require('express')

const app = express()
const secretKey = "gwy No1 @"
// 导入用于生成JWT字符串的包
const jwt = require('jsonwebtoken')

// 导入用于将客户端发送过来的JWT字符串，解析还原成 JSON对象
var {expressjwt: expressJWT} = require('express-jwt')
app.use(expressJWT({secret: secretKey, algorithms:["HS256"]}).unless({path: [/^\/api\//]}))

app.use(express.urlencoded({extended: false}))

app.get('/admin/getinfo', (req, res) => {
    console.log(req.user);

    res.send({
        status: 0,
        msg: "获取字符串成功",
        data: req.auth
    })
})


// 登录接口
app.post('/api/login', (req, res) => {
    const userinfo = req.body
     // 判断用户提交的信息是否正确
     if (userinfo.username !== 'admin' || userinfo.password !== '000000') {
        return res.send({status: 1, msg: '登录失败'})
    }

    const tokenStr = jwt.sign(userinfo, secretKey, {expiresIn : '30s'})
    res.send({ 
        status:0, 
        msg: '登录成功',
        token: tokenStr
    })
})

// 注册一个错误中间件
app.use((err, req, res, next) => {
    // 解析token失败
    if (err.username === 'UnauthorizedError') {
        return res.send({status:401, msg: '无效token'})
    }

    // 其它原因的错误
    res.send({status: 500, msg: '未知错误'})
})


app.listen(80, () => {
    console.log('express server runing at http://127.0.0.1');
})